import re
import time

from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.http import HttpResponseBadRequest
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.category.models import Category, Article, IPADDR

from apps.comments.models import Comments
from apps.index.utils import hanhan


class CategoryView(View):
    """show article' preview"""

    def get(self, request, num):
        # according the num read category content

        try:
            category = Category.objects.get(id=num)  # get category
            articles = category.article_set.all()  # get article

        except DatabaseError:
            return HttpResponseBadRequest("发生了预期之外的错误，返回后重试")

        context = hanhan()  # use that self function
        context['name'] = category.name  # category name
        context['articles'] = articles  # present category's articles

        return render(request, 'base_category.html', context=context)


class PersonalArticle(LoginRequiredMixin, View):
    def get(self, request):
        # according the num read category content
        user = request.user
        id = user.id
        articles = Article.objects.filter(article_use_id=id)

        name = '我的文章'

        context = hanhan()  # use that self function
        context['name'] = name  # category name
        context['articles'] = articles  # present category's articles

        return render(request, 'base_category.html', context=context)


class ArticleDetailView(View):
    """article detail"""

    def get(self, request, id):
        """according the click get what article detail"""
        t = time.time()
        IP = request.META['REMOTE_ADDR']

        try:
            article = Article.objects.get(id=id)
        except DatabaseError:
            return HttpResponseBadRequest('发生了预期之外的错误，返回后重试')
        category = article.category

        pca = category.article_set.all()  # present category's  all articles
        try:
            comments = article.comments_set.all()
        except DatabaseError:
            return HttpResponseBadRequest('显示评论失败,刷新一下试试')

        try:
            print('111')
            IP1=IPADDR.objects.get(ip_article_id=id,name=IP)
            print('222')
        except:
            article.views = article.views + 1
            article.save()
            IPADDR.objects.create(name=IP, ip_article=article,time=t)

        else:
            t1=IP1.time
            print('---------',t1)
            if t-t1>604800:
                article.views = article.views + 1
                article.save()
                IPADDR.objects.create(name=IP, ip_article=article, time=t)
            else:
                pass


        aritcles = Article.objects.all().order_by('-date')
        context = hanhan()  # use that self function
        context['article'] = article
        context['pca'] = pca
        context['comments'] = comments
        context['articles'] = aritcles
        return render(request, 'base_article.html', context=context)


class EditView(LoginRequiredMixin, View):
    """announce article"""

    def get(self, request):

        return render(request, 'announce.html')

    def post(self, request):
        # pre=request.META['HTTP_REFERER']
        user = request.user
        title = request.POST.get('title')
        content = request.POST.get('content')
        category = request.POST.get('category')
        tag = request.POST.get('tag')
        try:
            Article.objects.create(title=title, content=content, category_id=category, tag_id=tag, article_use=user)

        except:
            return HttpResponseBadRequest('文章发布失败，返回后重试')

        return redirect(reverse('index:index'))


class Alter(LoginRequiredMixin, View):
    """alter aritcle"""

    def get(self, request):
        global global_url
        user = request.user
        global_url = request.META['HTTP_REFERER']
        if 'article' in global_url:
            try:
                ret = re.match(r'(.*)/(\d+)/', global_url)
            except Exception:
                return HttpResponseBadRequest('请求非法！')

            id = int(ret.group(2))
            try:
                article = Article.objects.get(id=id)

                if article.article_use_id != user.id:
                    return HttpResponseBadRequest('无操作权限')
            except DatabaseError:
                return HttpResponseBadRequest('发生了不可预知的错误')


        else:
            return HttpResponseBadRequest('请先跳转到想要修改的文章详情页！')

        context = {"article": article,
                   }

        return render(request, 'alter.html', context)

    def post(self, request):

        # get parm
        title = request.POST.get('title')
        content = request.POST.get('content')
        category = request.POST.get('category')
        tag = request.POST.get('tag')
        url = global_url  # preurl
        if 'article' in global_url:
            try:
                ret = re.match(r'(.*)/(\d+)/', global_url)
            except Exception:
                return HttpResponseBadRequest('请求非法！')

        article_id = int(ret.group(2))
        try:
            article = Article.objects.get(id=article_id)
        except DatabaseError:
            return HttpResponseBadRequest('提交时发生了不可预知的错误')
        else:
            if title == '' or content == '':
                return HttpResponseBadRequest('标题或文章内容不能为空')
            else:
                article.title = title
                article.content = content

                article.category_id = category
                article.tag_id = tag
                article.save()

        return redirect(url)


global_url = ''
print('--------------->', global_url)


class Delete(View):
    """delete article"""

    def post(self, request):

        if 'article' in global_url:
            try:
                ret = re.match(r'(.*)/(\d+)/', global_url)
            except Exception:
                return HttpResponseBadRequest('请求非法！')

        article_id = int(ret.group(2))

        try:
            article = Article.objects.get(id=article_id)
        except DatabaseError:
            return HttpResponseBadRequest('删除时发生了不可预知的错误')
        else:
            article.delete()

        return redirect(reverse('index:index'))
